package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.dao.CategoryDao;
import com.itheima.dao.DishDao;
import com.itheima.dto.DishDto;
import com.itheima.po.Category;
import com.itheima.po.Dish;
import com.itheima.po.DishFlavor;
import com.itheima.service.CategoryService;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class DishServiceImpl extends ServiceImpl<DishDao, Dish> implements DishService {
    @Autowired
    private DishFlavorService dishFlavorService;
    @Autowired
    private DishService dishService;

    @Override
    public void saveWithFlavor(DishDto dishDto) {
        //        1、保存菜品 单条 mybatis-plus生成一个雪花算法的ID
        this.save(dishDto);//保存时会生成一个雪花算法的ID
        //        2、保存菜品口味 多条batch
        List<DishFlavor> flavorList = dishDto.getFlavors();
        for (DishFlavor dishFlavor : flavorList) {
            dishFlavor.setDishId(dishDto.getId());
        }
        dishFlavorService.saveBatch(flavorList);
    }

    @Override
    public void updateWithFlavor(DishDto dishDto) {
//        后端人员将数据保存到数据库，覆盖原有数据 dish覆盖 dish_flavor先删后插入
        this.updateById(dishDto);
        LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(lambdaQueryWrapper);
//        dishDto中的Flavors里的数据没有dish id
        List<DishFlavor> flavorList = dishDto.getFlavors();//缺少ID
        for (DishFlavor dishFlavor : flavorList) {
            dishFlavor.setDishId(dishDto.getId());
        }
        dishFlavorService.saveBatch(flavorList);
    }


}
